package com.ly.airline.controller;

import cn.hutool.core.bean.BeanUtil;
import com.ly.airline.pojo.*;
import com.ly.airline.service.HangbanService;
import com.ly.airline.service.OrderService;
import com.ly.airline.service.OrderitemService;
import com.ly.airline.utils.HttpResult;
import com.ly.airline.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author ：ly
 * @ClassName CarController
 * @date ：Created in 2022/4/29 15:08
 * @description： 购物车接口
 * @modified By：
 * @version: 1.0
 */
@Controller
@RequestMapping("cart")
public class CartController {
    @Autowired
    private HangbanService hangbanService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderitemService orderitemService;

    /**
     *@param model
	* @param request
     * @return java.lang.String
     * @author ly
     * @description: 用户获取购物车列表
     * @date 2022/4/30 0:03
     */
    @GetMapping("getCartList")
    public String getCarList(Model model, HttpServletRequest request){
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (BeanUtil.isEmpty(cart)){
            cart = new Cart();
        }
        model.addAttribute("cart",cart);
        return "qiantai/cart/mycart";
    }

    /**
     *@param orderitem
	* @param request
     * @return com.ly.airline.utils.HttpResult
     * @author ly
     * @description: 添加购物车
     * @date 2022/4/30 0:04
     */
    @PostMapping("addCart")
    @ResponseBody
    public HttpResult addCart(Orderitem orderitem,HttpServletRequest request){
        Hangban hangban = hangbanService.getById(orderitem.getHangbanid());
        //校验航班是否存在
        if (BeanUtil.isEmpty(hangban)){
            return HttpResult.success(false,"航班不存在");
        }
        //校验能够购买的票数是否足够
        if (orderitem.getShuliang()<=0||hangban.getShengpiao()<orderitem.getShuliang()){
            return HttpResult.success(false,"票数不足");
        }
        orderitem.setHangban(hangban);
        orderitem.setId(UUIDUtils.getUUID());
        //判断购买的是成人票还是儿童票，为订单项添加单价
        if (orderitem.getPiaoleixing().equals("成人票")){
            orderitem.setDanjia(hangban.getChengrenpiaojia());
        }else {
            orderitem.setDanjia(hangban.getErtongpiaojia());
        }
        //获取购物车
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (BeanUtil.isEmpty(cart)){
            cart = new Cart();
        }
        //添加购物车内容
        cart.addItem(orderitem.getHangbanid().toString()+orderitem.getPiaoleixing(),orderitem);
//        cart.setTotalPrice();
        request.getSession().setAttribute("cart",cart);
        return HttpResult.success(true,"已添加购物车");
    }

    /**
     *@param hangbanId
	* @param type
	* @param request
     * @return com.ly.airline.utils.HttpResult
     * @author ly
     * @description: 删除购物车
     * @date 2022/4/30 0:04
     */
    @GetMapping("deleteCart/{hangbanId}/{type}")
    @ResponseBody
    public HttpResult deleteCart(@PathVariable Integer hangbanId,@PathVariable String type,HttpServletRequest request){
        //获取购物车
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        //删除购物车中的指定订单项
        cart.deleteItem(hangbanId.toString()+type);
        //更新购物车
        request.getSession().setAttribute("cart",cart);
        return HttpResult.success(true,"删除成功");
    }

    /**
     *@param order
	* @param request
     * @return com.ly.airline.utils.HttpResult
     * @author ly
     * @description: 生成订单
     * @date 2022/4/30 0:05
     */
    @PostMapping("addOrder")
    @ResponseBody
    public HttpResult addOrder(Order order,HttpServletRequest request){
        //获取购物车
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        //获取登录用户
        User user = (User) request.getSession().getAttribute("user");
        //设置订单参数
        order.setId(UUIDUtils.getUUID());
        order.setUserId(user.getUserId());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        order.setXiadanshi(simpleDateFormat.format(new Date()));
        order.setZhuangtai("未受理");
        order.setZongjiage(cart.getTotalPrice());
        //遍历订单项
        Map<String, Orderitem> items = cart.getItems();
        for (Map.Entry<String, Orderitem> item : items.entrySet()) {
            Orderitem value = item.getValue();
            Hangban hangban = hangbanService.getById(value.getHangbanid());
            //判断航班剩余机票是否足够
            if (value.getShuliang()>hangban.getShengpiao()){
                continue;
            }
            value.setOrderid(order.getId());
            hangban.setShengpiao(hangban.getShengpiao()-value.getShuliang());
            //更新航班剩余机票
            hangbanService.updateById(hangban);
            //保存订单项
            orderitemService.save(value);
        }
        //保存订单
        orderService.save(order);


        return HttpResult.success(true,"下单成功");
    }
}
